package main

import (
	"context"
	"flag"
	"os"

	conf "admin_template/bff/admin/internal/base/config"
	"admin_template/bff/admin/internal/base/data"

	toolsConf "gitee.com/byx_darwin/go-tools/config"
	"gitee.com/byx_darwin/uptrace-opentelemetry/log"
	"gitee.com/byx_darwin/uptrace-opentelemetry/otelplay"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/polarismesh/polaris-go/pkg/model"
	"gopkg.in/yaml.v3"
)

var (
	namespace = "template"          //空间名称
	fileGroup = "bff"               //分组名称
	fileName  = "admin/config.yaml" //文件名称文件名称
	Data      = new(data.Data)
)

func main() {
	flag.Parse()
	config := new(conf.Config)
	ctx := context.Background()

	if conf.GetEnv() == "dev" || conf.GetEnv() == "test" {
		// 解析本地配置
		config = conf.GetConf()
	} else {
		if len(os.Args) > 1 {
			namespace = os.Args[1]
		}
		if len(os.Args) > 2 {
			fileGroup = os.Args[2]
		}
		if len(os.Args) > 3 {
			fileName = os.Args[3]
		}
		// 解析远程配置文件
		configFile, err := toolsConf.ConfigPolarisApi(namespace, fileGroup, fileName, ConfigFileChangeEvent)
		if err != nil {
			hlog.CtxFatalf(ctx, "配置文件 polaris.ConfigApi error：%v", err)
		}
		err = yaml.Unmarshal([]byte(configFile.GetContent()), &config)
		if err != nil {
			hlog.CtxFatalf(ctx, "配置文件 yaml反序列化失败 error：%v", err)
		}
	}
	// 自定义日志配置
	if config.ServerOption.Jaeger.Enable {
		shutdown := otelplay.ConfigureOpentelemetry(ctx, &otelplay.Config{
			ServiceDSN:     config.ServerOption.Jaeger.Endpoint,
			ServiceName:    config.ServerOption.Registry.Name,
			ServiceVersion: config.ServerOption.Registry.Version,
			Environment:    config.ServerOption.Registry.Env,
		})
		defer shutdown()
	}
	log.NewHertzLog(config.LogOption)
	Data, cleanup, err := data.NewData(hlog.DefaultLogger(), config)
	if err != nil {
		hlog.CtxFatalf(ctx, "Data 初始化失败 error：%v", err)
	}
	defer cleanup()
	// wire 依赖注入
	h, cleanup, err := initApp(Data)
	if err != nil {
		hlog.CtxFatalf(ctx, "初始化失败 error：%v", err)
	}
	defer cleanup()
	h.Spin()
}
func ConfigFileChangeEvent(event model.ConfigFileChangeEvent) {
	config := new(conf.Config)
	err := yaml.Unmarshal([]byte(event.NewValue), config)
	if err != nil {
		ctx := context.Background()
		hlog.CtxFatalf(ctx, "更新配置文件 yaml反序列化失败 error：%v", err)
	}
	Data.WithConfig(config)
}
